<template>
  <div class="acrticle-list">
    <van-pull-refresh success-duration="800" :success-text="pullText" v-model="isPullLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem v-for="item in list" :key="item.art_id+''" :articleItem="item">

        </ArticleItem>
      </van-list>

    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticleList } from '@/api/article'
import { Toast } from 'vant'
import ArticleItem from '@/components/ArticleItem'

export default {
  name: 'ArticleList',
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  components: {
    ArticleItem
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      pre_timestamp: null,
      error: false,
      isPullLoading: false,
      pullText: ''
    }
  },
  methods: {

    async onLoad () {
      // 1.发送请求数据
      // 2.保存数据
      // 3.加载状态结束
      // 4.数据全部加载完成
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.pre_timestamp || Date.now(),
          with_top: 1
        })
        this.pre_timestamp = res.pre_timestamp
        this.list.push(...res.results)
        this.loading = false
        if (!res.pre_timestamp) this.finished = true
      } catch (e) {
        Toast.clear()
        this.loading = false

        this.error = true
      }
    },
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg()
        }
        this.isPullLoading = false
        this.list.unshift(...res.results)
        this.pullText = '刷新成功'
      } catch (e) {
        this.isPullLoading = false
        this.pullText = '刷新失败'
      }
    }
  }

}
</script>

<style scoped lang='less'>
.acrticle-list {
  height: 80vh;
  overflow: scroll;

}

</style>
